# ブックマーク一覧取得APIクラス

require "rb/api.rb"
require "rb/lib/json.rb"

$KCODE = "UTF"

class GetBookmarksAPI < API

    def initialize
        super
        @paging = parse_request_for_paging()
        @conditions = parse_request_for_conditions()
        print bookmarks_by_jsonp()
    end

    def bookmarks_by_jsonp

        return attach_callback "{}" unless check_auth

        # 検索条件に合致しない行を削除する
        bookmarks = get_bookmarks().reverse().delete_if do |bookmark|

            # 全ての検索単語がtitleとcommentのいずれかにマッチしない 行を削除する
            unmatches = @conditions["keywords"].dup().delete_if do |i|
                next(true) if bookmark["title"] =~ Regexp.new(i)
                next(true) if bookmark["comment"] =~ Regexp.new(i)
                false
            end
            if @conditions["keywords"].length > 0 && unmatches.length > 0 then
                next(true)
            end

            # タグ条件が指定有る かつ 行のタグがタグ条件全てを含まない
            (@conditions["tags"].length > 0 && (@conditions["tags"] - bookmark["tags"]).length > 0)
        end

        # ページング処理
        total_count = bookmarks.length
        c_start = (@paging["page_count"] - 1) * @paging["display_count"]
        c_end = @paging["page_count"] * @paging["display_count"] - 1
        c_end = total_count - 1 if c_end + 1 >= total_count
        bookmarks = bookmarks[c_start..c_end]

        return attach_callback(JsonBuilder.new.build({
            "bookmarks" => bookmarks,
            "paging" => {
                "page_count" => @paging["page_count"],
                "total_page_count" => (total_count.to_f() / @paging["display_count"]).ceil(),
                "previous_page_count" => @paging["page_count"] == 1 ? nil : @paging["page_count"] - 1,
                "next_page_count" => c_end + 1 == total_count ? nil : @paging["page_count"] + 1,
                "display_count" => @paging["display_count"],
                "total_count" => total_count,
                "start_count" => c_start + 1,
                "end_count" => c_end + 1,
            },
        }))
    end

    def attach_callback(json_str)
        return 'Obm.getBookmarksAPICallBack(' + json_str + ');'
    end

    def parse_request_for_paging
        pc = @cgi["page_count"].to_i() > 0 ? @cgi["page_count"].to_i() : 1
        dc = @cgi["display_count"].to_i() > 0 ? @cgi["display_count"].to_i() : 10
        {
            "page_count" => pc,
            "display_count" => dc,
        }
    end

    def parse_request_for_conditions
        {
            "tags" => @cgi["tags"].split(/\t+/),
            # \xE3\x80\x80 は UTF-8 の全角空白
            "keywords" => @cgi["keywords"].split(/(\s|\xE3\x80\x80)+/).delete_if {|i| i == ""},
        }
    end
end

